<?php

/*
  +------------------------------------------------------+
  | 设计开发：Webster	Tel:17095135002	邮箱：312549912@qq.com	   |
  +------------------------------------------------------+
 */

namespace Home\Controller;
use Home\Controller\BaseController;
use Think\Controller;

class WxpayController extends BaseController {

    //初始化
    public function _initialize() {
        //获取来源地址
        $URL['PHP_SELF'] = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : (isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : $_SERVER['ORIG_PATH_INFO']);   //当前页面名称
        $URL['DOMAIN'] = $_SERVER['SERVER_NAME'];  //域名(主机名)
        $URL['QUERY_STRING'] = $_SERVER['QUERY_STRING'];   //URL 参数
        $URL['URI'] = $URL['PHP_SELF'] . ($URL['QUERY_STRING'] ? "?" . $URL['QUERY_STRING'] : "");
        $this->fromurl = "http://" . $URL['DOMAIN'] . $URL['PHP_SELF'] . ($URL['QUERY_STRING'] ? "_" . $URL['QUERY_STRING'] : ""); //完整URL地址
    }

    public function JsApipay() {
        $key = I('key');
        $ids = auth_decode($key);
        $order = M('order')->where('pay_sn=%s', array($ids))->count();
        //单个支付和合并支付
        if($order == 1){
            //循环获取订单的总价格和商品
            $orders = M('order')->where('pay_sn=%s', array($ids))->find();
            //获取订单下的商品
            $orderGoods = M('order_goods')->where('order_id=%s', array($orders['order_id']))->select();
            foreach ($orderGoods as $key => $value) {
                $title .= $value['goods_title'] .'；';
            }
            $title = "共".count($orderGoods)."件商品：". sub_str($title, 0, 22);
            $payPrice = $orders['goods_amount'];
        }else{
            $orders = M('order')->where('pay_sn=%s', array($ids))->select();
            foreach ($orders as $key => $value) {
                $payPrice  += $value['goods_amount'];
            }
            $title = "合并支付丨".$order."笔订单";
        }
        
        //获取平台的优惠券的信息
        $map['pay_sn'] = $ids;
        $map['voucher_store'] = 0;
        $tddList = M('order_voucher')->where($map)->select();
        if(!empty($tddList)){
            foreach ($tddList as $key => $value) {
                $totalTdd += $value['voucher_price'];
            }
            $payPrice = $payPrice-$totalTdd;
        }

        //全局引入微信支付类
        Vendor('Wxpay.WxPayPubHelper.WxPayPubHelper');
        
        //向Pay表里面添加一条数据
        $pay['id'] = time() . rand(1000, 9999);
        $pay['pay_sn'] = $ids;
        $pay['paytype'] = 'weixin';
        $pay['title'] = $title;
        $pay['user_id'] = session('user_id');
        $pay['callback'] = \WxPayConf_pub::NOTIFY_URL;
        $pay['total'] = $payPrice;
        $pay['created'] = NOW_TIME;
        M('orderPay')->add($pay);
        
        //使用jsapi接口
        $jsApi = new \JsApi_pub();
        //=========步骤1：网页授权获取用户openid============
        //通过code获得openid
        $openid = session('wx_openid');
        //=========步骤2：使用统一支付接口，获取prepay_id============
        //使用统一支付接口
        $unifiedOrder = new \UnifiedOrder_pub();

        //设置统一支付接口参数
        //设置必填参数
        //appid已填,商户无需重复填写
        //mch_id已填,商户无需重复填写
        //noncestr已填,商户无需重复填写
        //spbill_create_ip已填,商户无需重复填写
        //sign已填,商户无需重复填写
        $unifiedOrder->setParameter("openid", $openid); //商品描述
        $unifiedOrder->setParameter("body", $title); //商品描述
        //
        //自定义订单号
        $out_trade_no = $ids;
        $unifiedOrder->setParameter("out_trade_no", $out_trade_no); //商户订单号
        $unifiedOrder->setParameter("total_fee", $payPrice * 100); //总金额
        $unifiedOrder->setParameter("notify_url", \WxPayConf_pub::NOTIFY_URL); //通知地址
        $unifiedOrder->setParameter("trade_type", "JSAPI"); //交易类型
        //非必填参数，商户可根据实际情况选填
        //$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号
        //$unifiedOrder->setParameter("device_info","XXXX");//设备号
        //$unifiedOrder->setParameter("attach","XXXX");//附加数据
        //$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
        //$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间
        //$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记
        //$unifiedOrder->setParameter("openid","XXXX");//用户标识
        //$unifiedOrder->setParameter("product_id","XXXX");//商品ID
        $prepay_id = $unifiedOrder->getPrepayId();
        //=========步骤3：使用jsapi调起支付============
        $jsApi->setPrepayId($prepay_id);

        $jsApiParameters = $jsApi->getParameters();
        $this->assign('jsApiParameters', $jsApiParameters);
        $this->display();
    }
    
    public function JsApipays() {
        $key = I('key');
        $ids = auth_decode($key);
        //循环获取订单的总价格和商品
        $where['order_id'] = $ids;
        $orders = M('order')->where($where)->find();
        //获取订单下的商品
        $orderGoods = M('order_goods')->where($where)->select();
        foreach ($orderGoods as $key => $value) {
            $title .= $value['goods_title'] . '；';
        }
        $title = "共" . count($orderGoods) . "件商品：" . sub_str($title, 0, 22);
        $payPrice = $orders['goods_amount'];
        
        //获取平台的优惠券的信息
        $totalTdd = Snapup($ids, $orders['pay_sn']);
        $payPrice = $payPrice-$totalTdd;
        
        //全局引入微信支付类
        Vendor('Wxpay.WxPayPubHelper.WxPayPubHelper');

        //使用jsapi接口
        $jsApi = new \JsApi_pub();
        //=========步骤1：网页授权获取用户openid============
        //通过code获得openid
        $openid = session('wx_openid');
        //=========步骤2：使用统一支付接口，获取prepay_id============
        //使用统一支付接口
        $unifiedOrder = new \UnifiedOrder_pub();
        
            //自定义订单号
            $out_trade_no = create_trade_id();
            //更新订单的支付单号
            M('order')->where($where)->save(array('pay_sn'=>$out_trade_no));
            //向Pay表里面添加一条数据
            $pay['id'] = time() . rand(1000, 9999);
            $pay['pay_sn'] = $out_trade_no;
            $pay['paytype'] = 'weixin';
            $pay['title'] = $title;
            $pay['user_id'] = session('user_id');
            $pay['callback'] = \WxPayConf_pub::NOTIFY_PAY_URL;
            $pay['total'] = $payPrice;
            $pay['created'] = NOW_TIME;
            M('orderPay')->add($pay);
        

        //sign已填,商户无需重复填写
        $unifiedOrder->setParameter("openid", $openid); //商品描述
        $unifiedOrder->setParameter("body", $title); //商品描述
        //
        $unifiedOrder->setParameter("out_trade_no", $out_trade_no); //商户订单号
        $unifiedOrder->setParameter("total_fee", $payPrice * 100); //总金额
        $unifiedOrder->setParameter("notify_url", \WxPayConf_pub::NOTIFY_PAY_URL); //通知地址
        $unifiedOrder->setParameter("trade_type", "JSAPI"); //交易类型
        $prepay_id = $unifiedOrder->getPrepayId();
        //=========步骤3：使用jsapi调起支付============
        $jsApi->setPrepayId($prepay_id);
        $jsApiParameters = $jsApi->getParameters();

        $this->assign('jsApiParameters', $jsApiParameters);
        $this->display('JsApipay');
    }
    
    //正常JSAPI支付通知
    public function paynotify() {
        Vendor('Wxpay.WxPayPubHelper.WxPayPubHelper');
        //使用通用通知接口
        $notify = new \Notify_pub();
        //存储微信的回调
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $notify->saveData($xml);
        //验证签名，并回应微信。
        //对后台通知交互时，如果微信收到商户的应答不是成功或超时，微信认为通知失败，
        //微信会通过一定的策略（如30分钟共8次）定期重新发起通知，
        //尽可能提高通知的成功率，但微信不保证通知最终能成功。
        if ($notify->checkSign() == FALSE) {
            $notify->setReturnParameter("return_code", "FAIL"); //返回状态码
            $notify->setReturnParameter("return_msg", "签名失败"); //返回信息
        } else {
            $notify->setReturnParameter("return_code", "SUCCESS"); //设置返回码
        }
        $returnXml = $notify->returnXml();
        echo $returnXml;
        if ($notify->checkSign() == TRUE) {
            if ($notify->data["return_code"] == "FAIL") {
                log_result($log_name, "【通信出错】:\n" . $xml . "\n");
            } elseif ($notify->data["result_code"] == "FAIL") {
                log_result($log_name, "【业务出错】:\n" . $xml . "\n");
            } else {
                $re = M("orderPay")->where(array('pay_sn' => $notify->data["out_trade_no"]))->find();
                if($re['status'] != 20){
                //更新支付表的状态
                $pay['result'] = serialize($notify->data);
                $pay['buyer_email'] = $notify->data['openid'];
                $pay['trade_no'] = $notify->data['transaction_id'];
                $pay['payment'] = $notify->data['cash_fee']/100;
                $pay['pay_time'] = NOW_TIME;
                $pay['status'] = 20;
                M("orderPay")->where(array('pay_sn' => $notify->data["out_trade_no"]))->save($pay);
                    $where['user_id'] = $re['user_id'];
                    M('users')->where($where)->setInc('user_points',$notify->data['cash_fee']/100);
                    M('users')->where($where)->setInc('user_integral',round($notify->data['cash_fee']/100));
                    M('users')->where($where)->setInc('user_orders',1);
                    
                    //增加商品表的销量
                    addGoodsSale($notify->data["out_trade_no"]);
                }
                //计算出多订单的相关支付的价格（除去优惠券实际支付的价格）
//                $map['order_sn'] = $notify->data["out_trade_no"];
//                $oModel = D('Order');
//                $oList = $oModel->relation('OrderCommon')->where($map)->find();
//                $arr = unserialize($oList['OrderCommon']['reciver_info']);
                //计算出多订单的相关支付的价格（除去优惠券实际支付的价格）
                $order_sn = $notify->data["out_trade_no"];
                M("order")->where(array('pay_sn' => $order_sn))->save(array('order_state' => 20, 'order_amount' => $notify->data['cash_fee']/100, 'payment_time' => time()));
                //例如：推送支付完成信息
                //$notify->setReturnParameter("return_code", "SUCCESS");
                
                //给用户发送订单信息（微信）
                $template = array('touser' => $notify->data['openid'],
                    'template_id' => "8qbT8TlI1aQJUEXCTJYoRLbnjXkWkQJkT1QT-xVJVtM",
                    'url' => WEIXIN_URL."/Order/waitSend.html",
                    'topcolor' => "#7b68ee",
                    'data' => array('first' => array('value' => urlencode("您好,您购买的商品已经支付成功："),
                            'color' => "#000000",
                        ),
                        'keyword1' => array('value' => $notify->data["out_trade_no"],
                            'color' => "#000000",
                        ),
                        'keyword2' => array('value' => '支付成功',
                            'color' => "#000000",
                        ),
                        'keyword3' => array('value' => urlencode(date("Y-m-d H:i:s",time())),
                            'color' => "#000000",
                        ),
                        'keyword4' => array('value' => '淘嘟嘟商城',
                            'color' => "#000000",
                        ),
                        'keyword5' => array('value' => price($notify->data['cash_fee'] / 100),
                            'color' => "#ff0000",
                        ),
                        'remark' =>array('value'=>urlencode("\\n订单号：".$notify->data["out_trade_no"]."\\n您的订单已提交，我们将尽快为您发货！\\n如有疑问请拨打：4000371775！"),
                                    'color'=>"#000000",
                                ),
                    )
                );
                $result = urldecode(json_encode($template));
                $kefu = new \Libs\WeiXin\CustomService();
                $kefu->send_template_message($result);
                //此处应该更新一下订单状态，商户自行增删操作
                //log_result($log_name, "【支付成功】:\n" . $xml . "\n");
                //例如：推送支付完成信息
                $notify->setReturnParameter("return_code", "SUCCESS");
                
            }
        }
    }
    
    

    //正常JSAPI支付通知
    public function notify() {

        Vendor('Wxpay.WxPayPubHelper.WxPayPubHelper');
        //使用通用通知接口
        $notify = new \Notify_pub();

        //存储微信的回调
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $notify->saveData($xml);

        //验证签名，并回应微信。
        //对后台通知交互时，如果微信收到商户的应答不是成功或超时，微信认为通知失败，
        //微信会通过一定的策略（如30分钟共8次）定期重新发起通知，
        //尽可能提高通知的成功率，但微信不保证通知最终能成功。
        if ($notify->checkSign() == FALSE) {
            $notify->setReturnParameter("return_code", "FAIL"); //返回状态码
            $notify->setReturnParameter("return_msg", "签名失败"); //返回信息
        } else {
            $notify->setReturnParameter("return_code", "SUCCESS"); //设置返回码
        }
        $returnXml = $notify->returnXml();
        echo $returnXml;

        //==商户根据实际情况设置相应的处理流程，此处仅作举例=======
        //以log文件形式记录回调信息
//                 $log_ = new Log_();
        $log_name = __ROOT__ . "/Public/Weixin/notify_url.log"; //log文件路径
        log_result($log_name, "【接收到的notify通知】:\n" . $xml . "\n");

        if ($notify->checkSign() == TRUE) {
            if ($notify->data["return_code"] == "FAIL") {
                log_result($log_name, "【通信出错】:\n" . $xml . "\n");
            } elseif ($notify->data["result_code"] == "FAIL") {
                log_result($log_name, "【业务出错】:\n" . $xml . "\n");
            } else {
                $re = M("orderPay")->where(array('pay_sn' => $notify->data["out_trade_no"]))->find();
                if($re['status'] != 20){
                //更新支付表的状态
                $pay['result'] = serialize($notify->data);
                $pay['buyer_email'] = $notify->data['openid'];
                $pay['trade_no'] = $notify->data['transaction_id'];
                $pay['payment'] = $notify->data['cash_fee'] / 100;
                $pay['pay_time'] = NOW_TIME;
                $pay['status'] = 20;
                M("orderPay")->where(array('pay_sn' => $notify->data["out_trade_no"]))->save($pay);
                
                    $where['user_id'] = $re['user_id'];
                    M('users')->where($where)->setInc('user_points',$notify->data['cash_fee']/100);
                    M('users')->where($where)->setInc('user_integral',round($notify->data['cash_fee']/100));
                    M('users')->where($where)->setInc('user_orders',1);
                    
                    //增加商品表的销量
                    addGoodsSale($notify->data["out_trade_no"]);
                }
                $order_sn = $notify->data["out_trade_no"];
                $money = $notify->data['cash_fee']/100;
                //M("order")->where(array('pay_sn' => $order_sn))->save(array('order_state' => 20, 'order_amount' => $notify->data['cash_fee'] / 100, 'payment_time' => time()));
                //计算出多订单的相关支付的价格（除去优惠券实际支付的价格）
                
            $map['pay_sn'] = $order_sn;
            $oModel = D('Order');
            $oList = $oModel->relation('OrderGoods')->where($map)->select();
            //获取平台的优惠券的信息
            $maps['pay_sn'] = $order_sn;
            $maps['voucher_store'] = 0;
            $tddList = M('order_voucher')->where($maps)->select();
            if (!empty($tddList)) {
                foreach ($tddList as $key => $value) {
                    $totalTdd += $value['voucher_price'];
                }
            }
            $bili = (1 - $totalTdd/($money+$totalTdd)); //平台优惠比例
            foreach ($oList as $key => $value) {
                if ($value['discount_fee'] > 0) {
                    foreach ($value['OrderGoods'] as $k => $v) {
                        $pay_price[$k] = $bili * $v['goods_price'] * $v['goods_num'];
                        $trader_price += $bili * $v['goods_price'] * $v['goods_num'];
                    }
                    $bili2 = (1 - ($value['discount_fee']/$trader_price));
                    //根据占比更新单个商品时间支付的价格
                    foreach ($value['OrderGoods'] as $k => $v) {
                        //更新实际支付的价格
                        $pay[$k] = $bili2 * $pay_price[$k];
                        //在根据店铺的优惠比例继续计算实际支付的价格
                        M('OrderGoods')->where(array('order_id' => $v['order_id'], 'goods_id' => $v['goods_id']))->save(array('goods_pay_price' => $pay[$k]));
                        $total_price[$key] += $pay_price[$k];  //计算出订单的总价格
                    }
                    //更新订单的价格及状态
                    M("order")->where(array('order_id' => $value['order_id']))->save(array('order_state' => 20, 'order_amount' => $total_price[$key], 'payment_time' => time()));
                } else {
                    //根据占比更新单个商品时间支付的价格
                    foreach ($value['OrderGoods'] as $k => $v) {
                        //更新实际支付的价格
                        $pay_price[$k] = $bili * $v['goods_price']*$v['goods_num'];
                        M('OrderGoods')->where(array('order_id' => $v['order_id'], 'goods_id' => $v['goods_id']))->save(array('goods_pay_price' => $pay_price[$k]));
                        $total_price[$key] += $pay_price[$k];  //计算出订单的总价格
                    }
                    //更新订单的价格及状态
                    M("order")->where(array('order_id' => $value['order_id']))->save(array('order_state' => 20, 'order_amount' => $total_price[$key], 'payment_time' => time()));
                }
            }
                
                
                
                
//                    
//                    
//                $map['pay_sn'] = $notify->data["out_trade_no"];
//                $oLists = $oModel->relation('OrderCommon')->where($map)->find();
//                $arr = unserialize($oLists['OrderCommon']['reciver_info']);
                //给用户发送订单信息（微信）
                $template = array('touser' => $notify->data['openid'],
                    'template_id' => "8qbT8TlI1aQJUEXCTJYoRLbnjXkWkQJkT1QT-xVJVtM",
                    'url' => WEIXIN_URL."/Order/waitSend.html",
                    'topcolor' => "#7b68ee",
                    'data' => array('first' => array('value' => urlencode("您好,您购买的商品已经支付成功："),
                            'color' => "#000000",
                        ),
                        'keyword1' => array('value' => $notify->data["out_trade_no"],
                            'color' => "#000000",
                        ),
                        'keyword2' => array('value' => '支付成功',
                            'color' => "#000000",
                        ),
                        'keyword3' => array('value' => urlencode(date("Y-m-d H:i:s",time())),
                            'color' => "#000000",
                        ),
                        'keyword4' => array('value' => '淘嘟嘟商城',
                            'color' => "#000000",
                        ),
                        'keyword5' => array('value' => price($notify->data['cash_fee'] / 100),
                            'color' => "#ff0000",
                        ),
                        'remark' =>array('value'=>urlencode("\\n订单号：".$notify->data["out_trade_no"]."\\n您的订单已提交，我们将尽快为您发货！\\n如有疑问请拨打：4000371775！"),
                                    'color'=>"#000000",
                       ),
                    )
                );
                $result = urldecode(json_encode($template));
                $kefu = new \Libs\WeiXin\CustomService();
                $kefu->send_template_message($result);
                    
                //发送消息
//                $html = "<a href='http://m.taodudu.com/Wheel/turntable'>点击抽奖</a>";
//                $kefu->sendText($notify->data['openid'],'恭喜您获得一次抽奖免单机会！'.$html);
                
                //此处应该更新一下订单状态，商户自行增删操作
                //log_result($log_name, "【支付成功】:\n" . $xml . "\n");

                //例如：推送支付完成信息
                $notify->setReturnParameter("return_code", "SUCCESS");
            }
        }
    }
    
    
    
    
    

    //AA组团购JSAPI支付通知
    public function Gnotify() {

        Vendor('Wxpay.WxPayPubHelper.WxPayPubHelper');
        //使用通用通知接口
        $notify = new \Notify_pub();

        //存储微信的回调
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $notify->saveData($xml);

        //验证签名，并回应微信。
        //对后台通知交互时，如果微信收到商户的应答不是成功或超时，微信认为通知失败，
        //微信会通过一定的策略（如30分钟共8次）定期重新发起通知，
        //尽可能提高通知的成功率，但微信不保证通知最终能成功。
        if ($notify->checkSign() == FALSE) {
            $notify->setReturnParameter("return_code", "FAIL"); //返回状态码
            $notify->setReturnParameter("return_msg", "签名失败"); //返回信息
        } else {
            $notify->setReturnParameter("return_code", "SUCCESS"); //设置返回码
        }
        $returnXml = $notify->returnXml();
        echo $returnXml;

        //==商户根据实际情况设置相应的处理流程，此处仅作举例=======
        //以log文件形式记录回调信息
        //         $log_ = new Log_();
        //$log_name = __ROOT__ . "/Public/Weixin/notify_url.log"; //log文件路径
        //log_result($log_name, "【接收到的notify通知】:\n" . $xml . "\n");

        if ($notify->checkSign() == TRUE) {
            if ($notify->data["return_code"] == "FAIL") {
                log_result($log_name, "【通信出错】:\n" . $xml . "\n");
            } elseif ($notify->data["result_code"] == "FAIL") {
                log_result($log_name, "【业务出错】:\n" . $xml . "\n");
            } else {
                //更新支付表的状态
                $pay['result'] = serialize($notify->data);
                $pay['buyer_email'] = $notify->data['openid'];
                $pay['trade_no'] = $notify->data['transaction_id'];
                $pay['payment'] = $notify->data['cash_fee'] / 100;
                $pay['pay_time'] = NOW_TIME;
                $pay['status'] = 20;
                M("orderPay")->where(array('trade_id' => $notify->data["out_trade_no"]))->save($pay);
                M("vrOrder")->where(array('order_sn' => $notify->data["out_trade_no"]))->save(array('order_state' => 20, 'trade_no' => $notify->data['transaction_id'], 'order_amount' => $notify->data['cash_fee'] / 100, 'payment_time' => time()));
                //例如：推送支付完成信息
                $notify->setReturnParameter("return_code", "SUCCESS");
                //此处应该更新一下订单状态，商户自行增删操作
                log_result($log_name, "【支付成功】:\n" . $xml . "\n");
            }
        }
    }

    //扫码微信支付模式一
    public function native_pay() {
        //全局引入微信支付类
        Vendor('Wxpay.WxPayPubHelper.WxPayPubHelper');
        //设置静态链接
        $nativeLink = new \NativeLink_pub();

        //设置静态链接参数
        //设置必填参数
        //appid已填,商户无需重复填写
        //mch_id已填,商户无需重复填写
        //noncestr已填,商户无需重复填写
        //time_stamp已填,商户无需重复填写
        //sign已填,商户无需重复填写
        $product_id = \WxPayConf_pub::APPID . "static"; //自定义商品id
        $nativeLink->setParameter("product_id", $product_id); //商品id
        //获取链接
        $product_url = $nativeLink->getUrl();
        //使用短链接转换接口
        $shortUrl = new \ShortUrl_pub();
        //设置必填参数
        //appid已填,商户无需重复填写
        //mch_id已填,商户无需重复填写
        //noncestr已填,商户无需重复填写
        //sign已填,商户无需重复填写
        $shortUrl->setParameter("long_url", $product_url); //URL链接
        //获取短链接
        $codeUrl = $shortUrl->getShortUrl();
        $this->assign('product_url', $product_url);
        $this->assign('codeUrl', $codeUrl);
        $this->display();
    }

    //扫码支付通知
    public function todoPost() {
        //全局引入微信支付类
        Vendor('Wxpay.WxPayPubHelper.WxPayPubHelper');
        //以log文件形式记录回调信息，用于调试
        $log_name = __ROOT__ . "/Public/Weixin/native_call.log";
        //使用native通知接口
        $nativeCall = new \NativeCall_pub();

        //接收微信请求
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        log_result($log_name, "【接收到的native通知】:\n" . $xml . "\n");
        $nativeCall->saveData($xml);

        if ($nativeCall->checkSign() == FALSE) {
            $nativeCall->setReturnParameter("return_code", "FAIL"); //返回状态码
            $nativeCall->setReturnParameter("return_msg", "签名失败"); //返回信息
        } else {
            //提取product_id
            $product_id = $nativeCall->getProductId();

            //使用统一支付接口
            $unifiedOrder = new \UnifiedOrder_pub();

            //根据不同的$product_id设定对应的下单参数，此处只举例一种
            switch ($product_id) {

                case \WxPayConf_pub::APPID . "static"://与native_call_qrcode.php中的静态链接二维码对应
                    //设置统一支付接口参数
                    //设置必填参数
                    //appid已填,商户无需重复填写
                    //mch_id已填,商户无需重复填写
                    //noncestr已填,商户无需重复填写
                    //spbill_create_ip已填,商户无需重复填写
                    //sign已填,商户无需重复填写
                    $unifiedOrder->setParameter("body", "贡献一分钱"); //商品描述
                    //自定义订单号，此处仅作举例
                    $timeStamp = time();
                    $out_trade_no = \WxPayConf_pub::APPID . $timeStamp;
                    $unifiedOrder->setParameter("out_trade_no", $out_trade_no); //商户订单号             $unifiedOrder->setParameter("product_id","$product_id");//商品ID
                    $unifiedOrder->setParameter("total_fee", "1"); //总金额
                    $unifiedOrder->setParameter("notify_url", \WxPayConf_pub::NOTIFY_URL); //通知地址
                    $unifiedOrder->setParameter("trade_type", "NATIVE"); //交易类型
                    $unifiedOrder->setParameter("product_id", $product_id); //用户标识
                    //非必填参数，商户可根据实际情况选填
                    //$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号
                    //$unifiedOrder->setParameter("device_info","XXXX");//设备号
                    //$unifiedOrder->setParameter("attach","XXXX");//附加数据
                    //$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
                    //$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间
                    //$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记
                    //$unifiedOrder->setParameter("openid","XXXX");//用户标识
                    //获取prepay_id
                    $prepay_id = $unifiedOrder->getPrepayId();
                    //设置返回码
                    //设置必填参数
                    //appid已填,商户无需重复填写
                    //mch_id已填,商户无需重复填写
                    //noncestr已填,商户无需重复填写
                    //sign已填,商户无需重复填写
                    $nativeCall->setReturnParameter("return_code", "SUCCESS"); //返回状态码
                    $nativeCall->setReturnParameter("result_code", "SUCCESS"); //业务结果
                    $nativeCall->setReturnParameter("prepay_id", $prepay_id); //预支付ID

                    break;
                default:
                    //设置返回码
                    //设置必填参数
                    //appid已填,商户无需重复填写
                    //mch_id已填,商户无需重复填写
                    //noncestr已填,商户无需重复填写
                    //sign已填,商户无需重复填写
                    $nativeCall->setReturnParameter("return_code", "SUCCESS"); //返回状态码
                    $nativeCall->setReturnParameter("result_code", "FAIL"); //业务结果
                    $nativeCall->setReturnParameter("err_code_des", "此商品无效"); //业务结果
                    break;
            }
        }

        //将结果返回微信
        $returnXml = $nativeCall->returnXml();
        log_result($log_name, "【返回微信的native响应】:\n" . $returnXml . "\n");

        echo $returnXml;
    }

    //微信扫码支付 模式2
    public function paymentConfirm() {

        $key = I('get.key');
        $ids = auth_decode($key);
        
        $order = M('order')->where('pay_sn=%s', array($ids))->count();
        //单个支付和合并支付
        if($order == 1){
            //循环获取订单的总价格和商品
            $orders = M('order')->where('pay_sn=%s', array($ids))->find();
            //获取订单下的商品
            $orderGoods = M('order_goods')->where('order_id=%s', array($orders['order_id']))->select();
            foreach ($orderGoods as $key => $value) {
                $title .= $value['goods_title'] .'；';
            }
            $title = "共".count($orderGoods)."件商品：". sub_str($title, 0, 22);
            $payPrice = $orders['goods_amount'];
        }else{
            $orders = M('order')->where('pay_sn=%s', array($ids))->select();
            foreach ($orders as $key => $value) {
                $payPrice  += $value['goods_amount'];
            }
            $title = "合并支付丨".$order."笔订单";
        }
        //获取平台的优惠券的信息
        $map['pay_sn'] = $ids;
        $map['voucher_store'] = 0;
        $tddList = M('order_voucher')->where($map)->select();
        if(!empty($tddList)){
            foreach ($tddList as $key => $value) {
                $totalTdd += $value['voucher_price'];
            }
            $payPrice = $payPrice-$totalTdd;
        }
        //全局引入微信支付类
        Vendor('Wxpay.WxPayPubHelper.WxPayPubHelper');
        
        //向Pay表里面添加一条数据
        $pay['id'] = time() . rand(1000, 9999);
        $pay['pay_sn'] = $ids;
        $pay['paytype'] = 'weixin';
        $pay['title'] = $title;
        $pay['user_id'] = session('user_id');
        $pay['callback'] = \WxPayConf_pub::NOTIFY_URL;
        $pay['total'] = $payPrice;
        $pay['created'] = NOW_TIME;
        M('orderPay')->add($pay);
        
        //使用统一支付接口
        $unifiedOrder = new \UnifiedOrder_pub();

        $unifiedOrder->setParameter("body", $title); //商品描述
        //自定义订单号，此处仅作举例
        $out_trade_no = $ids;
        $unifiedOrder->setParameter("out_trade_no", $out_trade_no); //商户订单号
        $unifiedOrder->setParameter("total_fee", $payPrice * 100); //总金额
        //$unifiedOrder->setParameter("attach", $attach); //附加数据
        $unifiedOrder->setParameter("notify_url", \WxPayConf_pub::NOTIFY_URL); //通知地址 
        $unifiedOrder->setParameter("trade_type", "NATIVE"); //交易类型
        //非必填参数，商户可根据实际情况选填
        //$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号  
        //$unifiedOrder->setParameter("device_info","XXXX");//设备号 
        //$unifiedOrder->setParameter("attach","XXXX");//附加数据 
        //$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
        //$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间 
        //$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记 
        //$unifiedOrder->setParameter("openid","XXXX");//用户标识
        //$unifiedOrder->setParameter("product_id","XXXX");//商品ID
        //获取统一支付接口结果
        $unifiedOrderResult = $unifiedOrder->getResult();

        //商户根据实际情况设置相应的处理流程
        if ($unifiedOrderResult["return_code"] == "FAIL") {
            //商户自行增加处理流程
            echo "通信出错：" . $unifiedOrderResult['return_msg'] . "<br>";
        } elseif ($unifiedOrderResult["result_code"] == "FAIL") {
            //商户自行增加处理流程
            echo "错误代码：" . $unifiedOrderResult['err_code'] . "<br>";
            echo "错误代码描述：" . $unifiedOrderResult['err_code_des'] . "<br>";
        } elseif ($unifiedOrderResult["code_url"] != NULL) {
            //从统一支付接口获取到code_url
            $code_url = $unifiedOrderResult["code_url"];
            //商户自行增加处理流程
            //......
        }
        $this->assign('out_trade_no', $out_trade_no);
        $this->assign('code_url', $code_url);
        $this->assign('unifiedOrderResult', $unifiedOrderResult);
        $this->assign('payPrice', $payPrice);
        $this->assign('title', $title);
        $this->assign('orders', $orders);
        $this->display();
    }

    //刷卡支付
    public function micropay() {
        Vendor('Wxpay.WxPayMicropayHelper.WxPayMicropayHelper');
        //自定义订单号，此处仅作举例
        $timeStamp = time();
        $out_trade_no = \WxPayConf_micropay::APPID . $timeStamp;

        //获取用户一维码
        if (isset($_POST["auth_code"])) {
            $auth_code = $_POST["auth_code"];

            //使用被扫支付接口
            $micropayCall = new \MicropayCall();

            //设置被扫支付接口参数
            //设置必填参数
            //appid已填,商户无需重复填写
            //mch_id已填,商户无需重复填写
            //noncestr已填,商户无需重复填写
            //spbill_create_ip已填,商户无需重复填写
            //sign已填,商户无需重复填写
            $micropayCall->setParameter("body", "贡献一分钱"); //商品描述
            $micropayCall->setParameter("out_trade_no", "$out_trade_no"); //商户订单号
            $micropayCall->setParameter("total_fee", "1"); //总金额
            $micropayCall->setParameter("auth_code", "$auth_code"); //交易类型
            //非必填参数，商户可根据实际情况选填
            //$micropayCall->setParameter("sub_mch_id","XXXX");//子商户号
            //$micropayCall->setParameter("device_info","XXXX");//设备号
            //$micropayCall->setParameter("attach","XXXX");//附加数据
            //$micropayCall->setParameter("time_start","XXXX");//交易起始时间
            //$micropayCall->setParameter("time_expire","XXXX");//交易结束时间
            //$micropayCall->setParameter("goods_tag","XXXX");//商品标记
            //$micropayCall->setParameter("openid","XXXX");//用户标识
            //$micropayCall->setParameter("product_id","XXXX");//商品ID
            //提交订单
            $micropayCallResult = $micropayCall->getResult();

            //商户根据实际情况设置相应的处理流程,此处仅作举例
            if ($micropayCallResult["return_code"] == "FAIL") {
                echo "通信出错：" . $micropayCallResult['return_msg'] . "<br>";
            } elseif ($micropayCallResult["result_code"] == "FAIL") {
                echo "出错" . "<br>";
                echo "错误代码：" . $micropayCallResult['err_code'] . "<br>";
                echo "错误代码描述：" . $micropayCallResult['err_code_des'] . "<br>";
            } else {
                echo "用户标识：" . $micropayCallResult['openid'] . "<br>";
                echo "是否关注公众账号：" . $micropayCallResult['is_subscribe'] . "<br>";
                echo "交易类型：" . $micropayCallResult['trade_type'] . "<br>";
                echo "付款银行：" . $micropayCallResult['bank_type'] . "<br>";
                echo "总金额：" . $micropayCallResult['total_fee'] . "<br>";
                echo "现金券金额：" . $micropayCallResult['coupon_fee'] . "<br>";
                echo "货币种类：" . $micropayCallResult['fee_type'] . "<br>";
                echo "微信支付订单号：" . $micropayCallResult['transaction_id'] . "<br>";
                echo "商户订单号：" . $micropayCallResult['out_trade_no'] . "<br>";
                echo "商家数据包：" . $micropayCallResult['attach'] . "<br>";
                echo "支付完成时间：" . $micropayCallResult['time_end'] . "<br>";
            }
        } else {
            $this->assign('out_trade_no', $out_trade_no);
            $this->display();
        }
    }

    //发送现金红包
    public function sendRedpack() {
        header("Access-Control-Allow-Origin:*");
        //全局引入微信支付类
        Vendor('Wxpay.WxPayPubHelper.WxPayPubHelper');
        //调用请求接口基类
        $Redpack = new \Redpack_pub();

        //=========步骤1：网页授权获取用户openid============
        //通过code获得openid
        //$openid = session('wx_openid');
        $openid = $Redpack->getOpenId();
        $timeStamp = time();
        //商户订单号
        $Redpack->setParameter('mch_billno', \WxPayConf_pub::APPID . $timeStamp);
        //提供方名称
        $Redpack->setParameter('nick_name', "淘嘟嘟电子商务网");
        //商户名称
        $Redpack->setParameter('send_name', "淘嘟嘟电子商务网");
        //用户openid
        //$Redpack->setParameter('re_openid', $openid);
        //付款金额
        $Redpack->setParameter('total_amount', 100);
        //最小红包金额
        $Redpack->setParameter('min_value', 100);
        //最大红包金额
        $Redpack->setParameter('max_value', 100);
        //红包发放总人数
        $Redpack->setParameter('total_num', 1);
        //红包祝福语
        $Redpack->setParameter('wishing', "现金红包祝大家工作快乐");
        //活动名称
        $Redpack->setParameter('act_name', "淘嘟嘟月底活动！");
        //备注
        $Redpack->setParameter('remark', "现金红包祝大家工作快乐");
        //以下是非必填项目
        //子商户号  
//         $Redpack->setParameter('sub_mch_id', $parameterValue);
//        //商户logo的url
//         $Redpack->setParameter('logo_imgurl', $parameterValue);
//         //分享文案
//         $Redpack->setParameter('share_content', $parameterValue);
//         //分享链接
//         $Redpack->setParameter('share_url', $parameterValue);
//         //分享的图片
//         $Redpack->setParameter('share_imgurl', $parameterValue);
        $result = $Redpack->sendRedpack();
        p($result);
        exit;
        //红包中奖记录
        $data['user_id'] = session('user_id');
        $data['open_id'] = $result['re_openid'];
        $data['nickname'] = session('user_id');
        $data['money'] = $result['total_amount'];
        $data['addtime'] = NOW_TIME;
        $re = M('redpacks')->add($data);

        if ($re) {
            $this->success('红包已经发送到您手机，请注意查收！');
        } else {
            $this->error('系统异常，请稍后再试！');
        }
    }

    
    //发送裂变红包
    public function sendRedpacks() {
        //全局引入微信支付类
        Vendor('Wxpay.WxPayPubHelper.WxPayPubHelper');
        //调用请求接口基类
        $Redpack = new \Groupredpack_pub();

        //=========步骤1：网页授权获取用户openid============
        //通过code获得openid
        $openid = $Redpack->getOpenId();
        //商户订单号
        $timeStamp = time();
        $Redpack->setParameter('mch_billno', \WxPayConf_pub::APPID . $timeStamp);
        //商户名称
        $Redpack->setParameter('send_name', "淘嘟嘟电子商务网");
        //接受红包的种子用户
        //$Redpack->setParameter('re_openid', $openid);
        //付款金额
        $Redpack->setParameter('total_amount', 100);
        //红包发放总人数
        $Redpack->setParameter('total_num', 10);
        $Redpack->setParameter('amt_type', 'ALL_RAND');
        //红包祝福语
        $Redpack->setParameter('wishing', "分裂红包测试！");
        //活动名称
        $Redpack->setParameter('act_name', "本奖品由韩盼龙提供！");
        //备注
        $Redpack->setParameter('remark', "祝大家工作愉快！！！");
        //以下是非必填项目
        //子商户号
        //         $Redpack->setParameter('sub_mch_id', $parameterValue);
        //        //商户logo的url
        //         $Redpack->setParameter('amt_list', '200|100|100');

        $result = $Redpack->sendRedpack();
        p($result);
        exit;
        //红包中奖记录
        $data['user_id'] = session('user_id');
        $data['open_id'] = $result['re_openid'];
        $data['nickname'] = session('user_id');
        $data['money'] = $result['total_amount'];
        $data['addtime'] = NOW_TIME;
        $re = M('redpacks')->add($data);

        if ($re) {
            $this->success('红包已经发送到您手机，请注意查收！');
        } else {
            $this->error('系统异常，请稍后再试！');
        }
    }

    
    //查询订单的支付状态
    public function payStatus() {
        $out_trade_no = I('tradeno');
        $re = M("Order")->where('pay_sn=' . $out_trade_no)->find();
        if ($re && $re['order_state'] == '20') {
            $data['status'] = 1;
            $data['msg'] = '订单支付成功';
        }else{
            $data['status'] = 0;
        }
        $this->ajaxReturn($data);
    }

}
